package com.wechat.core.handler;

import com.wechat.core.annotation.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 默认拦截器
 */
@Slf4j
public class DefaultAuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        return getUser(httpServletRequest, httpServletResponse, object);
    }

    /**
     * 登录校验
     *
     * @param httpServletRequest
     * @param object
     * @return
     */
    private boolean getUser(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            return true;
        }
        if (httpServletRequest.getRequestURI().contains("swagger") || httpServletRequest.getRequestURI().contains("error")) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 白名单校验
        if (this.passToken(method)) {
            return true;
        }
        LoginBean loginBean=tokenUtil.loginValidate(httpServletRequest,httpServletResponse);

        httpServletRequest.setAttribute("token", loginBean.getToken());
        httpServletRequest.setAttribute("userId", loginBean.getUserId());
        httpServletRequest.setAttribute("openId", loginBean.getOpenId());

        return true;
    }

    /**
     * token校验器
     *
     * @param method HandlerMethod
     * @return
     */
    private boolean passToken(Method method) {
        if (method.isAnnotationPresent(Token.class)) {
            Token passToken = method.getAnnotation(Token.class);
            if (passToken != null && !passToken.required()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
